import React, { createContext, useContext, useReducer, ReactNode } from 'react';

// Agent状态类型定义
interface AgentState {
  agents: Map<string, {
    definition: any;
    baseAgent: any;
    mcpClient: any;
    toolsEnabled: boolean;
  }>;
  currentAgent: string | null;
  isProcessing: boolean;
}

// Agent动作类型
type AgentAction = 
  | { type: 'SET_AGENTS'; payload: Map<string, any> }
  | { type: 'SET_CURRENT_AGENT'; payload: string | null }
  | { type: 'SET_PROCESSING'; payload: boolean }
  | { type: 'UPDATE_AGENT_TOOLS'; payload: { agentId: string; toolsEnabled: boolean } }
  | { type: 'RESET_AGENTS' };

// 初始状态
const initialState: AgentState = {
  agents: new Map(),
  currentAgent: null,
  isProcessing: false,
};

// Reducer函数
function agentReducer(state: AgentState, action: AgentAction): AgentState {
  switch (action.type) {
    case 'SET_AGENTS':
      return { ...state, agents: action.payload };
    case 'SET_CURRENT_AGENT':
      return { ...state, currentAgent: action.payload };
    case 'SET_PROCESSING':
      return { ...state, isProcessing: action.payload };
    case 'UPDATE_AGENT_TOOLS':
      const newAgents = new Map(state.agents);
      const agent = newAgents.get(action.payload.agentId);
      if (agent) {
        newAgents.set(action.payload.agentId, {
          ...agent,
          toolsEnabled: action.payload.toolsEnabled
        });
      }
      return { ...state, agents: newAgents };
    case 'RESET_AGENTS':
      return initialState;
    default:
      return state;
  }
}

// Context类型
interface AgentContextType {
  state: AgentState;
  dispatch: React.Dispatch<AgentAction>;
  // 便捷方法
  setAgents: (agents: Map<string, any>) => void;
  setCurrentAgent: (agentId: string | null) => void;
  setProcessing: (processing: boolean) => void;
  updateAgentTools: (agentId: string, toolsEnabled: boolean) => void;
  resetAgents: () => void;
  // 计算属性
  getAgent: (agentId: string) => any;
  getEnabledAgents: () => any[];
  getAllAgents: () => any[];
}

// 创建Context
const AgentContext = createContext<AgentContextType | undefined>(undefined);

// Provider组件
interface AgentProviderProps {
  children: ReactNode;
}

export function AgentProvider({ children }: AgentProviderProps) {
  const [state, dispatch] = useReducer(agentReducer, initialState);

  // 便捷方法
  const setAgents = (agents: Map<string, any>) => {
    dispatch({ type: 'SET_AGENTS', payload: agents });
  };

  const setCurrentAgent = (agentId: string | null) => {
    dispatch({ type: 'SET_CURRENT_AGENT', payload: agentId });
  };

  const setProcessing = (processing: boolean) => {
    dispatch({ type: 'SET_PROCESSING', payload: processing });
  };

  const updateAgentTools = (agentId: string, toolsEnabled: boolean) => {
    dispatch({ type: 'UPDATE_AGENT_TOOLS', payload: { agentId, toolsEnabled } });
  };

  const resetAgents = () => {
    dispatch({ type: 'RESET_AGENTS' });
  };

  // 计算属性
  const getAgent = (agentId: string) => {
    return state.agents.get(agentId);
  };

  const getEnabledAgents = () => {
    return Array.from(state.agents.values()).filter(agent => agent.toolsEnabled);
  };

  const getAllAgents = () => {
    return Array.from(state.agents.values());
  };

  const contextValue: AgentContextType = {
    state,
    dispatch,
    setAgents,
    setCurrentAgent,
    setProcessing,
    updateAgentTools,
    resetAgents,
    getAgent,
    getEnabledAgents,
    getAllAgents,
  };

  return (
    <AgentContext.Provider value={contextValue}>
      {children}
    </AgentContext.Provider>
  );
}

// Hook
export function useAgent() {
  const context = useContext(AgentContext);
  if (context === undefined) {
    throw new Error('useAgent must be used within an AgentProvider');
  }
  return context;
}

// 便捷Hook
export function useAgentStatus() {
  const { state, getEnabledAgents, getAllAgents } = useAgent();
  
  return {
    ...state,
    enabledAgents: getEnabledAgents(),
    allAgents: getAllAgents(),
  };
}
